package sysytmRepo

import (
	"gorm.io/gorm"
	"ruoyi/domain/entity/common"
	"ruoyi/domain/entity/system"
	"ruoyi/domain/repository"
)

type sysUserRoleRepo struct {
	db *gorm.DB
}

func SysUserRoleRepository(db *gorm.DB) *sysUserRoleRepo {
	return &sysUserRoleRepo{db}
}

var _ repository.SysUserRoleRepository = &sysUserRoleRepo{}

func (r *sysUserRoleRepo) SelectSysUserRoleList(params common.SearchTableDataParam, isPage bool) common.TableDataInfo {

	var pageNum = params.PageNum
	var pageSize = params.PageSize
	sysUserRole := params.Other.(system.SysUserRole)

	offset := (pageNum - 1) * pageSize
	var total int64
	var rows []system.SysUserRole

	var db = r.db.Model(&system.SysUserRole{}).
		Joins("left join sys_dept d on d.dept_id = dept_id").
		Select("*, d.dept_name, d.leader")

	db.Where("del_flag = '0'")
	var userId = sysUserRole.UserId
	if userId != 0 {
		db.Where("user_id = ?", userId)
	}
	if err := db.Count(&total).Error; err != nil {
		return common.Fail()
	}
	if isPage {
		if err := db.Limit(pageSize).Offset(offset).Find(&rows).Error; err != nil {
			return common.Fail()
		}
	} else {
		if err := db.Find(&rows).Error; err != nil {
			return common.Fail()
		}
	}

	if rows == nil {
		return common.Fail()
	} else {
		return common.Success(rows, total)
	}

}
